package com.xyw.code.bus.common.util;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/2/18
 * Time: 下午9:39
 * Email: 1328312923@qq.com
 * Description: No Description
 **/
@Component
@Slf4j
public class MQReceiver {

    @Autowired
    private MessageSendAsync messageSendAsync;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "boot.queue1", durable = "true"),
                    exchange = @Exchange(value = "BOOT-EXCHANGE-1", type = "topic", durable = "true", ignoreDeclarationExceptions = "true"),
                    key = "boot.*"
            )
    )
    @RabbitHandler
    public void process7(Message message, Channel channel) throws Exception {
        // 模拟消费者代码异常，这种情况必须在catch块设置重试次数（也可以在配置文件中全局设置重试次数，当然百度的方案都不行，所以我没成功过），防止死循环
        // catch块中重试可用redis的自增来做计数器，从而控制重试次数
        try {
            int i = 1/0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // redelivered = true, 表明该消息是重复处理消息
            System.out.println("消息投放失败:" +  new String(message.getBody()));
            messageSendAsync.dealFailMessage(message,channel);
        }
    }

}